<?php

namespace app\backend\controller;

use app\backend\model\Account as AccountDao;
use houdunwang\crypt\Crypt;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use think\Session;

class Account extends Controller
{
    protected $accountDao;

    public function __construct(Request $request, AccountDao $accountDao)
    {
        parent::__construct($request);
        $this->accountDao = $accountDao;
    }

    public function login()
    {
        $userInfo = Session::get('userInfo');

        if (empty($userInfo['admin_id']))
        {
            return $this->fetch();
        }
        $this->redirect(url('backend/Index/index'));
    }

    public function reg()
    {
        return $this->fetch();
    }

    public function pass()
    {
        return $this->fetch();
    }

    public function user()
    {
        return $this->fetch();
    }

    /**登陆功能
     * @param Request $request
     * @return array
     */
    public function doLogin(Request $request)
    {
        $vars = $request->param();
//        $res = $this->validate($vars, 'Account.login');
//        if (true !== $res) {
//            return ['status' => 0, 'msg' => $res];
//        }
        try {
            $user = $this->accountDao->where('admin_username', $vars['username'])->find();
        } catch (Exception $e) {
            return ['status' => 0, 'msg' => $e->getMessage()];
        }

        if (is_null($user)) {
            return ['status' => 0, 'msg' => '账号不存在'];
        }

        if (true !== password_verify($vars['password'], $user['admin_password'])) {
            return ['status' => 0, 'msg' => '账号密码错误'];
        }

        $userInfo = [
            'admin_id' => $user['admin_id'],
            'admin_username' => $user['admin_username']
        ];
        Session::set('userInfo', $userInfo);

        return ['status' => 1, 'msg' => '登录成功'];
    }

    /**注册功能
     * 注册前，查询用户名是否存在
     * @param Request $request
     * @return array
     */
    public function doReg(Request $request)
    {
        $vars = $request->param();
        //加密前台的值
        $pass = password_hash($vars['password'], PASSWORD_BCRYPT, ['cost' => 10]);
        $res = $this->validate($vars, 'Account.reg');
        if (true !== $res) {
            return ['status' => 0, 'msg' => $res];
        }
        //查询用户名是否存在
        $name = $this->accountDao->where('admin_username', 'eq', $vars['username'])->find();
        if (!is_null($name))
        {
            return ['status' => 0, 'msg' => '用户名已存在'];
        }

        try {
            $user = $this->accountDao->allowField(true)->create([
                'admin_username' => $vars['username'],
                'admin_password' => $pass
            ]);
        } catch (Exception $e) {
            return ['status' => 0, 'msg' => $e->getMessage()];
        }

        if ($user !== false) {
            return ['status' => 1, 'msg' => 'succ'];
        }
        return ['status' => 0, 'msg' => 'faild'];
    }

    /**
     * 修改密码
     * 0.用户是否登陆
     * 1.根据用户session的id查出后台密码与前台拿过来的值相互比较
     * 2.需要修改的密码与重复密码要相等
     * 3.相同的密码要加密存储到后台
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updatePass(Request $request)
    {
        $vars = $request->param();
        //更新密码的是重复密码的值，直接把值加密
        $repeat_password = password_hash($vars['repeat_password'], PASSWORD_BCRYPT, ['cost' => 10]);
        //把session名为userInfo的session放入这个变量中
        $userInfo = session('userInfo');

        $session_admin_id = $userInfo['admin_id'];
        //根据当前登录用户的id查询这条记录
        $data = $this->accountDao->where("$session_admin_id=admin_id")->find();

        //登录验证
        if (empty($userInfo['admin_id'])) {
            return ['status' => 0, 'msg' => '请先登陆'];
        }
        //验证确认密码
        if ($vars['update_password'] !== $vars['repeat_password']) {
            return ['status' => 0, 'msg' => '新密码和重复密码不匹配'];
        }
        //验证原密码是否正确；后台密码与前台密码（前台密码可以无需加密）
        if (true !== password_verify($vars['password'], $data['admin_password'])) {
            return ['status' => 0, 'msg' => '原密码不正确'];
        }
        $this->accountDao->where('admin_id', $userInfo['admin_id'])->setField('admin_password', $repeat_password);
    }

    public  function delete(Request $request)
    {
        $vars = $request->param();
        $this->accountDao->destroy($vars['admin_id']);
        //$this->accountDao->where('admin_id','=',$vars['admin_id'])->delete();
        if (empty($vars['admin_id']))
        {
            return ['status' => 0, 'msg' => '缺少参数admin_id'];
        }
            return ['status' => 1, 'msg' => 'succ'];
    }

    public function logout()
    {
        Session::delete('userInfo');
        $this->redirect(url('backend/Account/login'));
    }
}